package com.app.controller;


import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.app.model.AdminUserModel;
import com.app.model.EnjoyEnterprise;
import com.app.model.UserModel;
import com.app.service.AdminUserService;
import com.app.service.EnjoyEnterpriseService;
import com.app.service.EnterpriseService;
import com.app.service.UserService;
import com.app.util.Result;
import com.app.util.TokenUtils;
import com.app.vo.EnjoyEnterpriseExportVo;
import com.app.vo.EnjoyEnterpriseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author shaokuiling
 * @since 2024-10-15
 */
@RestController
@RequestMapping("/enjoyEnterprise")
public class EnjoyEnterpriseController {
    @Autowired
    private EnjoyEnterpriseService enjoyEnterpriseService;
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    UserService userService;
    @Autowired
    private EnterpriseService enterpriseService;

    // 查询列表
    @GetMapping("/getEnjoyEnterpriseList")
    public Result getEnjoyEnterpriseList(@RequestParam(defaultValue = "0") Integer page,
                                         @RequestParam(defaultValue = "10") Integer limit, String name, HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if ("false".equals(userId)) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel userModel = adminUserService.getUserById(Integer.parseInt(userId));
        if (userModel == null) {
            return Result.error(405, "用户不存在");
        }
        EnjoyEnterpriseVo courseVo = enjoyEnterpriseService.getEnjoyEnterpriseList(page, limit, name, userModel);
        return Result.success(courseVo);
    }

    /**
     * 小程序列表
     *
     * @param page
     * @param limit
     * @param name
     * @param eid
     * @param request
     * @return
     */
    @GetMapping("/getEnjoyEnterprises")
    public Result getEnjoyEnterprises(@RequestParam(defaultValue = "0") Integer page,
                                      @RequestParam(defaultValue = "10") Integer limit, String name, Integer eid, HttpServletRequest request) {
        String token = request.getHeader("token");
        String mobile = TokenUtils.nothingness(token);
        if (mobile == null) {
            return Result.error(405, "token不存在");
        }

        UserModel user = userService.getUserByMobile(mobile);
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        EnjoyEnterpriseVo courseVo = enjoyEnterpriseService.getEnjoyEnterprises(page, limit, name, eid);
        return Result.success(courseVo);
    }

    //根据id查询
    @GetMapping("/getEnjoyEnterpriseById")
    public Result getCourseById(Integer id) {
        EnjoyEnterprise Course = enjoyEnterpriseService.getById(id);
        return Result.success(Course);
    }

    //新增和修改
    @PostMapping("/addAndUpdateEnjoyEnterprise")
    public Result addAndUpdateCourse(@RequestBody EnjoyEnterprise enjoyEnterprise, HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if ("false".equals(userId)) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel userModel = adminUserService.getUserById(Integer.parseInt(userId));
        if (userModel == null) {
            return Result.error(405, "用户不存在");
        }
        if (enjoyEnterprise.getPhone() != null && !enjoyEnterprise.getPhone().isEmpty()) {
            String mobileNumber = enjoyEnterprise.getPhone();
            if (!validateMobileNumber(mobileNumber)) {
                return Result.error(500, "人员手机号格式错误");
            }
        }
        if (enjoyEnterprise.getEphone() != null && !enjoyEnterprise.getEphone().isEmpty()) {
            String mobileNumber = enjoyEnterprise.getEphone();
            if (!validateMobileNumber(mobileNumber)) {
                return Result.error(500, "企业手机号格式错误");
            }
        }
        if (enjoyEnterprise.getId() != null) {
            enjoyEnterprise.setUpdateTime(new Date());
            enjoyEnterpriseService.updateById(enjoyEnterprise);
            return Result.success("修改成功");
        } else {
            enjoyEnterprise.setCreateTime(new Date());
            enjoyEnterpriseService.save(enjoyEnterprise);
            return Result.success("添加成功");
        }
    }

    //根据id删除
    @GetMapping("/delEnjoyEnterprise")
    public Result delCourse(Integer id) {
        enjoyEnterpriseService.removeById(id);
        return Result.success("删除成功");
    }

    /**
     * 账单导出
     *
     * @param response
     */
    @GetMapping("/enjoyEnterpriseExcel")
    public void enjoyEnterpriseExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String token = request.getHeader("token");
        if (token == null) {
            return;

        }
        String userId = TokenUtils.verify(token);
        if ("false".equals(userId)) {
            return;
        }
        AdminUserModel userModel = adminUserService.getUserById(Integer.parseInt(userId));
        if (userModel == null) {
            return;
        }

        //设置响应头
//        response.setContentType("application/vnd.ms-excel");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        //设置下载时的文件名
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日HH时mm分ss秒"));
        String fileName = "享受补助学生名单" + time + ".xlsx";
        //中文名编码格式设置
        fileName = URLEncoder.encode(fileName, "UTF-8");
        //文件下载方式（附件下载还是当前浏览器下载）
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        //构建写入到excel中的数据
        //获取列表
        List<EnjoyEnterprise> list = enjoyEnterpriseService.getEnjoyEnterpriseList(1, 10000, null, userModel).getList();
        ArrayList<EnjoyEnterpriseExportVo> enjoyEnterpriseExportVos = new ArrayList<>();
        for (EnjoyEnterprise o : list) {
            EnjoyEnterpriseExportVo exportVo = new EnjoyEnterpriseExportVo();
            BeanUtil.copyProperties(o, exportVo);
            enjoyEnterpriseExportVos.add(exportVo);
        }
//        // 输出文件内容到响应流中
        try (OutputStream outputStream = response.getOutputStream()) {
            EasyExcel.write(outputStream, EnjoyEnterpriseExportVo.class).sheet("模板").doWrite(enjoyEnterpriseExportVos);
        } catch (IOException e) {
            // 处理异常
        }
    }

    public boolean validateMobileNumber(String mobileNumber) {
        // 中国大陆手机号的正则表达式
        String regex = "^1[3-9]\\d{9}$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(mobileNumber);
        return matcher.matches();
    }

    @GetMapping("/getSelectEnterpriseById")
    public Result getSelectEnterpriseById(Integer id, HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if ("false".equals(userId)) {
            return Result.error(405, "token已过期");
        }
        AdminUserModel userModel = adminUserService.getUserById(Integer.parseInt(userId));
        if (userModel == null) {
            return Result.error(405, "用户不存在");
        }
        return Result.success(enterpriseService.getById(id));
    }

}

